package junit;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class RepeatRule implements TestRule {

  @Override
  public Statement apply(Statement statement, Description description) {
    Statement result = statement;
    Repeat repeat = description.getAnnotation(Repeat.class);
    if (repeat != null) {
      int times = repeat.value();
      result = new RepeatStatement(statement, times);
    }
    return result;
  }

  private static class RepeatStatement extends Statement {

    private final Statement statement;

    private final int repeat;

    public RepeatStatement(Statement statement, int repeat) {
      this.statement = statement;
      this.repeat = repeat;
    }

    @Override
    public void evaluate() throws Throwable {
      long totalTime = 0L;
      long maxTime = 0L;
      for (int i = 1; i <= repeat; i++) {
        long start = System.currentTimeMillis();
        statement.evaluate();
        long end = System.currentTimeMillis();
        long perTime = end - start;
        System.err.println("执行第" + i + "次测试花费时间为" + perTime + "毫秒" + "\n");
        totalTime += perTime;
        maxTime = Math.max(perTime, maxTime);
      }
      System.err
          .println("平均执行时间为" + (repeat > 1 ? (totalTime - maxTime) / repeat : totalTime / repeat));
    }

  }

}
